package com.zhouyu;

import com.zhouyu.service.UserService;
import org.springframework.cglib.proxy.*;

import java.lang.reflect.Method;

/**
 * @author leimingchao
 * create 2025-05-15 20:17
 */
public class TestCglib {

	public static void main(String[] args) {

		UserService target = new UserService();

		Enhancer enhancer = new Enhancer();

		enhancer.setSuperclass(UserService.class);

		enhancer.setCallbacks(new Callback[]{
				new MethodInterceptor() {
					/**
					 *
					 * @param o 代理对象
					 * @param method 被代理对象的方法
					 * @param objects 方法参数
					 * @param methodProxy 代理对象的方法
					 * @return
					 * @throws Throwable
					 */
					@Override
					public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

						System.out.println("before...");
						//被代理的方法，目标对象(被代理对象)
						//Object result = methodProxy.invoke(target, objects);

						//Object result = method.invoke(target, objects);


						//代理类的父类的方法
						Object result = methodProxy.invokeSuper(o, objects);


						System.out.println("after...");
						return result;
					}
				}, NoOp.INSTANCE
		});

		enhancer.setCallbackFilter(new CallbackFilter() {
			@Override
			public int accept(Method method) {
				if ("test".equals(method.getName())) {

					return 0;
				} else {
					return 1;
				}
			}
		});

		UserService userService = (UserService) enhancer.create();
		userService.a();
	}
}
